﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Alert_Form.Component.Alert;
using YXChatFormClient.Dtos.Account;
using YXChatFormClient.Global;
using YXChatFormClient.Utility;

namespace YXChatFormClient.UserControls
{
    public partial class UC_AccountCenter : UserControl
    {
        private readonly HttpHelper _http;
        public UC_AccountCenter()
        {
            _http = new HttpHelper();
            InitializeComponent();
            //设置控件样式
            SetStyle(
                ControlStyles.AllPaintingInWmPaint | //不闪烁
                ControlStyles.OptimizedDoubleBuffer //支持双缓存
                , true);
            var account = GlobalAccountInfo.Account;
            this.tbAccountNumber.Text = account.AccountNumber;
            this.tbNickName.Text = account.NickName;
            this.tbArea.Text = account.Area;
            this.tbSignature.Text = account.Signature;
            this.picAvatar.ImageLocation = ImageHelper.GetServerImage(account.Avatar);
            this.ckAutoLogin.Checked = JSONHelper.ReadJSON<bool>("IsAutoLogin");
            this.btnUpdate.Left += 70;
        }

        private async void UC_AccountCenter_Load(object sender, EventArgs e)
        {
            this.tbPassword.Text = await _http.GetAsync<string>($"{Api.GetAccountPwd}/{GlobalAccountInfo.Account.Id}");
            EnableControls(false);
        }
        private void EnableControls(bool flag)
        {
            this.tbNickName.Enabled = flag;
            this.tbArea.Enabled = flag;
            this.tbSignature.Enabled = flag;
            this.tbPassword.Enabled = flag;
            this.panel1.Visible = flag;
            this.panel2.Visible = flag;
            this.panel3.Visible = flag;
            this.panel5.Visible = flag;
            this.btnSave.Visible = flag;
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (this.btnUpdate.Text.Equals("修改信息"))
            {
                EnableControls(true);
                this.btnUpdate.Text = @"取消修改";
                this.btnUpdate.Left -= 70;
            }
            else
            {
                UC_AccountCenter_Load(null,null);
                this.btnUpdate.Text = @"修改信息";
                this.btnUpdate.Left += 70;
            }
        }

        private async void btnSave_Click(object sender, EventArgs e)
        {
            #region 校验
            if (tbNickName.Text.IsNullOrWhiteSpace())
            {
                AlertForm.ShowAlert(@"昵称不能为空",AlertType.Warning);
                return;
            }
            if (tbArea.Text.IsNullOrWhiteSpace())
            {
                AlertForm.ShowAlert(@"地区不能为空", AlertType.Warning);
                return;
            }
            if (tbSignature.Text.IsNullOrWhiteSpace())
            {
                AlertForm.ShowAlert(@"个性签名不能为空", AlertType.Warning);
                return;
            }
            if (tbPassword.Text.IsNullOrWhiteSpace())
            {
                AlertForm.ShowAlert(@"密码不能为空", AlertType.Warning);
                return;
            }
            if (tbPassword.Text.Length < 6)
            {
                AlertForm.ShowAlert(@"密码不能少于6位数", AlertType.Warning);
                return;
            }
            #endregion

            AccountEditDto editDto = new AccountEditDto()
            {
                Id = GlobalAccountInfo.Account.Id,
                AccountNumber = GlobalAccountInfo.Account.AccountNumber,
                Avatar = GlobalAccountInfo.Account.Avatar,
                PhoneNumber = GlobalAccountInfo.Account.PhoneNumber,
                Area = tbArea.Text,
                NickName = tbNickName.Text,
                Signature = tbSignature.Text,
                PassWord = tbPassword.Text
            };
            var output = await _http.PostAsync<UpdateAccountOutput>(Api.UpdateAccount, editDto);
            GlobalAccountInfo.Account = output.Account;
            AlertForm.ShowAlert(@"修改成功", AlertType.Success);
            btnUpdate_Click(null,null);
            if (output.IsUpdatePwd)
            {
                AlertForm.ShowAlert(@"您的密码已经修改,需重新登录",AlertType.Info ,
                    direction:ShowDirection.BottomRight);
                
            }
        }

        private async void btnOpenPic_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = openFilePic.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                // 获得文件的完整路径（包括名字后后缀）
                string filePath = openFilePic.FileName;

                using (Stream stream = openFilePic.OpenFile())
                {
                    byte[] bytes = new byte[stream.Length];
                    stream.Position = 0;
                    stream.Read(bytes, 0,(int)stream.Length);
                    stream.Close();
                    if (bytes.Length > 1024 * 200)
                    {
                        AlertForm.ShowAlert("图片不能大于200kb",AlertType.Warning,direction: ShowDirection.TopRight);
                        return;
                    }
                    // 将字节数组转换为文本base64
                    var avatarBase64 = Convert.ToBase64String(bytes);
                    UpdateAvatarDto dto = new UpdateAvatarDto
                    {
                        AccountNumber = GlobalAccountInfo.Account.AccountNumber,
                        AvatarBase64 = avatarBase64
                    };
                    var imgUrl = await _http.PostAsync<string>(Api.UpdateAccountAvatar, dto);
                    GlobalAccountInfo.AccountAvatar = imgUrl;
                    picAvatar.ImageLocation = ImageHelper.GetServerImage(imgUrl);
                }
            }
        }

        private void ckAutoLogin_CheckedChanged(object sender, EventArgs e)
        {
            JSONHelper.WriteJSON("IsAutoLogin",ckAutoLogin.Checked);
            JSONHelper.WriteJSON("PassWord", tbPassword.Text);
        }
    }
}
